package com.hankol.newretail

import android.graphics.Color
import android.text.TextUtils
import android.view.View
import androidx.lifecycle.Observer
import com.alibaba.android.arouter.facade.annotation.Route
import com.baselibrary.MessageBus
import com.baselibrary.extension.checkNotNull
import com.baselibrary.extension.checkValue
import com.baselibrary.extension.toast
import com.baselibrary.bean.CityData
import com.baselibrary.router.ActivityRouter
import com.baselibrary.utils.*
import com.bigkoo.pickerview.builder.OptionsPickerBuilder
import com.bigkoo.pickerview.view.OptionsPickerView
import com.baselibrary.activity.BaseActivity
import com.hankol.newretail.bean.AddressData
import com.baselibrary.bean.ReceiveAddressBean
import com.baselibrary.manager.CityManager
import com.hankol.newretail.databinding.ActivityEditOrNewAddAddressBinding
import com.hankol.newretail.viewmodel.AddressAboutViewModel
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.json.JSONException
import org.json.JSONObject

/**新零售-【编辑*新增】地址
 * @author: merbng
 * @time: 2022/8/5 9:48
 * @description:
 */
@Route(path = ActivityRouter.NEW_RETAIL.EDIT_OR_ADD_NEW_ADDRESS)
class EditOrNewAddAddressActivity : BaseActivity(), View.OnClickListener {
    private lateinit var viewModel: AddressAboutViewModel
    private lateinit var binding: ActivityEditOrNewAddAddressBinding
    var areaFirst = ""
    var areaSecond = ""
    var areaThree = ""

    var mAddressBean: ReceiveAddressBean? = null

    companion object {
        //需要修改的地址对象，如果为null 则 新增地址
        const val KEY_ADDRESS_BEAN = "key_address_bean"
    }

    override fun getLayoutId(): Int {
        return R.layout.activity_edit_or_new_add_address
    }

    override fun init() {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this)
        }
        binding = getDataBinding()
        viewModel = getActivityViewModelProvider(this).get(AddressAboutViewModel::class.java)
        if (intent.extras.checkNotNull()) {
            mAddressBean = intent.extras?.getParcelable<ReceiveAddressBean>(KEY_ADDRESS_BEAN)
        }
        initView()
        initListener()
        initObserver()
    }

    private fun initObserver() {
        viewModel.addAddressLD.observe(this, Observer {
            "新增成功".toast()
            EventBusUtils.sendNotify2Bean(selectAddressMessBus(it))
            finish()
        })
        viewModel.editAddressLD.observe(this, Observer {
            "修改成功".toast()
            EventBusUtils.sendNotify(MessageBus.msgId_new_add_address_success)
            finish()
        })
    }

    fun selectAddressMessBus(addressBean: ReceiveAddressBean): MessageBus {
        val builder = MessageBus.Builder()
        return builder.codeType(MessageBus.msgId_new_add_address_success).message(addressBean)
            .build();
    }

    private fun initListener() {
        binding.ivBack.setOnClickListener(this)
        binding.tvProvinceCity.setOnClickListener(this)
        binding.tvConfirm.setOnClickListener(this)
        binding.tvDefTitle.setOnClickListener(this)
    }

    private fun initView() {
        mCityList = CityManager.getInstance().areaFirst
        for (i in mCityList.indices) {
            val options2Items_01 = java.util.ArrayList<String>()
            val options3Items_01 = java.util.ArrayList<java.util.ArrayList<String>>()
            val province = mCityList[i].name
            for (j in mCityList[i].children.indices) {
                options2Items_01.add(mCityList[i].children[j].name)
                val options3Items_01_01 = java.util.ArrayList<String>()
                for (k in mCityList[i].children[j].children.indices) {
                    options3Items_01_01.add(mCityList[i].children[j].children[k].name)
                }
                options3Items_01.add(options3Items_01_01)
            }
            mOptionsItemSheng.add(province)
            mOptionsItemShi.add(options2Items_01)
            mOptionsItemQv.add(options3Items_01)
        }
        binding.tvTitle.text = "添加地址"
        mAddressBean?.let {
            binding.tvTitle.text = "编辑地址"
            //编辑--赋值
            binding.etName.setText(it.name.checkValue())
            binding.etPhone.setText(it.phone.checkValue())

            val name =
                AddressUtil.getAddressName(it.areaFirst) + AddressUtil.getAddressName(it.areaSecond) + AddressUtil.getAddressName(it.areaThree)
            mCityId.add(AddressUtil.getAddressId(it.areaFirst))
            mCityId.add(AddressUtil.getAddressId(it.areaSecond))
            mCityId.add(AddressUtil.getAddressId(it.areaThree))

            mCityName.add(AddressUtil.getAddressName(it.areaFirst))
            mCityName.add(AddressUtil.getAddressName(it.areaSecond))
            mCityName.add(AddressUtil.getAddressName(it.areaThree))
            binding.tvProvinceCity.setText(name)
            binding.etDetail.setText(it.address.checkValue())
            binding.cbDefault.isChecked = it.def == 1
        }
    }

    override fun onClick(v: View) {
        when (v.id) {
            R.id.iv_back -> {
                finish()
            }
            R.id.tv_province_city -> {//省市区选择
                if(DoubleClickHelper.isOnDoubleClick())return
                //选择地址
                KeyBoardUtils.hideSoftKeyboard(this)
                selectAddress()
            }
            R.id.tv_confirm -> {//确定
                if(DoubleClickHelper.isOnDoubleClick())return
                val name = binding.etName.text.toString().checkValue().trim()
                val phone = binding.etPhone.text.toString().checkValue()

                val address = binding.etDetail.text.toString().checkValue().trim()
                val def = if (binding.cbDefault.isChecked) 1 else 0

                if (mCityId.size>0) {
                    areaFirst = showName(AddressData(mCityId[0], mCityName[0]))
                    areaSecond = showName(AddressData(mCityId[1], mCityName[1]))
                    areaThree = showName(AddressData(mCityId[2], mCityName[2]))
                }
                if (TextUtils.isEmpty(name)) {
                    "请输入收货人姓名".toast()
                    return
                }
                if (TextUtils.isEmpty(phone)) {
                    ToastUtils.showShort(this, "请输入联系方式")
                    return
                }
                if (phone.length != 11) {
                    ToastUtils.showShort(this, "请输入正确的联系方式")
                    return
                } else if (!CommonUtil.isMobile(phone)) {
                    ToastUtils.showShort(this, "请输入正确的联系方式")
                    return
                }
                if (areaFirst.isNullOrEmpty()) {
                    "请选择您的所在地区".toast()
                    return
                }
                if (address.isNullOrEmpty()) {
                    "请填写详细地址".toast()
                    return
                }
                if (mAddressBean.checkNotNull()) {
                    //修改地址
                    viewModel.requestSaveEditAddressList("${mAddressBean?.id}", name, phone, areaFirst, areaSecond, areaThree, address, def)
                } else {
                    //新增地址
                    viewModel.requestNewAddAddressList(name, phone, areaFirst, areaSecond, areaThree, address, def)
                }
            }
            R.id.tv_def_title -> {
                binding.cbDefault.isChecked = !binding.cbDefault.isChecked
            }
        }
    }

    private var mCityList: List<CityData> = emptyList()
    private var mCityName = ArrayList<String>()
    private var mCityId = ArrayList<String>()
    private val mOptionsItemSheng = java.util.ArrayList<String>() //省
    private val mOptionsItemShi = java.util.ArrayList<java.util.ArrayList<String>>() //市
    private val mOptionsItemQv =
        java.util.ArrayList<java.util.ArrayList<java.util.ArrayList<String>>>() //区

    private fun selectAddress() {
        val pvOptions: OptionsPickerView<Any> =
            OptionsPickerBuilder(this) { options1, options2, options3, v ->
                mCityName = ArrayList<String>()
                mCityId = ArrayList<String>()
                for (i in mCityList.indices) {
                    if (mCityList.get(i).getId() === mCityList.get(options1).getId()) {
                        mCityName.add(mCityList.get(i).getName())
                        mCityId.add(mCityList.get(i).getId())
                        for (j in mCityList.get(i).getChildren().indices) {
                            if (mCityList.get(i).getChildren().get(j)
                                    .getId() === mCityList.get(options1).getChildren().get(options2)
                                    .getId()
                            ) {
                                mCityName.add(mCityList.get(i).getChildren().get(j).getName())
                                mCityId.add(mCityList.get(i).getChildren().get(j).getId())
                            }
                            for (k in mCityList.get(i).getChildren().get(j).getChildren().indices) {
                                if (mCityList.get(i).getChildren().get(j).getChildren().get(k)
                                        .getId() === mCityList.get(options1).getChildren()
                                        .get(options2).getChildren().get(options3).getId()
                                ) {
                                    mCityName.add(
                                        mCityList.get(i).getChildren().get(j).getChildren().get(k)
                                            .getName()
                                    )
                                    mCityId.add(
                                        mCityList.get(i).getChildren().get(j).getChildren().get(k)
                                            .getId()
                                    )
                                }
                            }
                        }
                    }
                }
                binding.tvProvinceCity.setText(
                    mCityName.get(0).toString() + " " + mCityName.get(1) + " " + mCityName.get(2)
                )
            }.setTitleText("城市选择").setTitleBgColor(Color.WHITE) //设置标题的背景颜色
                .setDividerColor(Color.BLACK) //设置分割线的颜色
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20).build<Any>()
        pvOptions.setPicker(mOptionsItemSheng.toList(), mOptionsItemShi.toList(), mOptionsItemQv.toList())
        pvOptions.show()
    }

    private fun showName(data: AddressData): String {
        try {
            val jsonObject = JSONObject()
            jsonObject.put("id", data.id)
            jsonObject.put("name", data.name)
            return jsonObject.toString()
        } catch (e: JSONException) {
            e.printStackTrace()
        }
        return ""
    }

    //EventBus 接受方法
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEvent(messageBus: MessageBus) {
        /*  if (messageBus.codeType == MessageBus.msgId_follow_and_cancel) {
              mViewModel.reqArticleDetail(aid)
          }*/
    }

    override fun onDestroy() {
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this)
        }
        super.onDestroy()
    }
}